package com.example.duanlei417.mypro2.login.lib_login.core;

import android.content.Context;

import com.example.duanlei417.mypro2.login.lib_login.annotation.LoginFilter;
import com.example.duanlei417.mypro2.login.lib_login.execption.AnnotationException;
import com.example.duanlei417.mypro2.login.lib_login.execption.NoInitException;


import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.reflect.Method;

/**
 * 处理LoginFilter注解
 */
@Aspect
public class LoginFilterAspect {
    private static final String TAG = "LoginFilterAspect";

    @Pointcut("execution(@com.example.duanlei417.mypro2.login.lib_login.annotation.LoginFilter * *(..))")
    public void loginFilter() {}

    @Around("loginFilter()")
    public void aroundLoginPoint(ProceedingJoinPoint joinPoint) throws Throwable {
        //标注1
        ILogin iLogin = LoginAssistant.getInstance().getILogin();
        if (iLogin == null) {
            throw new NoInitException("LoginSDK 没有初始化！");
        }

        //标注2
        Signature signature = joinPoint.getSignature();
        if (!(signature instanceof MethodSignature)) {
            throw new AnnotationException("LoginFilter 注解只能用于方法上");
        }
        MethodSignature methodSignature = (MethodSignature) signature;
        LoginFilter loginFilter = methodSignature.getMethod().getAnnotation(LoginFilter.class);
        if (loginFilter == null) {
            return;
        }

        Context param = LoginAssistant.getInstance().getApplicationContext();
        //标注3
        if (iLogin.isLogin(param)) {
            //已经登录执行标注的方法体
            joinPoint.proceed();
        } else { //没有登录，执行login方法
            //标注4
            Object target = joinPoint.getTarget();
            Method method = target.getClass().getMethod(methodSignature.getName(),
                    methodSignature.getParameterTypes());
            String name = method.getName();
            if (name.contains("lib_login_filter_onCreate")) {
                //标注5
                Object[] args = joinPoint.getArgs();
                if (args != null && args.length == 1 && (args[0] instanceof Boolean)) {
                    joinPoint.proceed(new Object[] {true});
                } else {
                    iLogin.login(param, loginFilter.userDefine());
                }
            } else {
                iLogin.login(param, loginFilter.userDefine());
            }
        }
    }
}

